package com.cheyunkeji.er.activity.evaluate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.evaluate.WaitToEvaluateListAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.BeforeArchiveListItem;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Michael on 2017/7/26 17:08.
 */

public class WaitToEvaluateActivity extends BaseActivity implements WaitToEvaluateListAdapter.OnItemActionListener, OnRefreshListener, OnLoadMoreListener {

    private static final String TAG = WaitToEvaluateActivity.class.getSimpleName();
    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.rl_empty_content_display)
    RelativeLayout rlEmptyContentDisplay;
    @BindView(R.id.swipe_target)
    ListView swipeTarget;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.tv_item_count)
    TextView tvItemCount;

    private int CURRENT_LOAD_PAGE = 1;

    private ArrayList<BeforeArchiveListItem> dataList;
    private WaitToEvaluateListAdapter adapter;

    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                onRefreshSuccessed((ArrayList<BeforeArchiveListItem>) msg.obj);
            } else {

                onLoadMoreSuccessed((ArrayList<BeforeArchiveListItem>) msg.obj);
            }
        }
    };

    @Override
    protected void init() {

        setContentView(R.layout.er_layout_wait_to_evaluate);
        ButterKnife.bind(this);

        dataList = new ArrayList<>();
        adapter = new WaitToEvaluateListAdapter(dataList, this);
        swipeTarget.setAdapter(adapter);
    }

    @Override
    protected void initView() {
        vTopbar.setTitle("待评估车辆");
        vTopbar.setLeftBack();
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
    }

    @Override
    protected void initData() { }

    public void loadBeforeCarList(int page, int rows) {

        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("page", String.valueOf(page));
        params.put("rows", String.valueOf(rows));

        ApiClient.postForm(HttpConstants.BEFORE_ARCHIVE_LIST, params, new RespCallback<List<BeforeArchiveListItem>>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onMsgCount(int rows) {
                super.onMsgCount(rows);
                setItemCount(rows);
            }

            @Override
            protected void onSuccess(List<BeforeArchiveListItem> data) {

                Log.e(TAG, "onSuccess: " + data.size());
                Log.e(TAG, "onSuccess: CURRENT PAGE INDEX : " + CURRENT_LOAD_PAGE);

                Message msg = uiRefreshHandler.obtainMessage();
                msg.obj = data;
                uiRefreshHandler.sendMessage(msg);

            }

            @Override
            public void onError(Exception e) {
                super.onError(e);

                if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                    swipeLayout.endRefresh();
                } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                    swipeLayout.endLoadMore();
                }
            }
        });
    }

    public void setItemCount(int itemCount ){
        tvItemCount.setText(String.format( "共%1$s条数据" , String.valueOf(itemCount)));
    }

    private void onRefreshSuccessed(ArrayList<BeforeArchiveListItem> newList) {
        if (newList != null && newList.size() != 0) {
            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE++;

        } else if (newList.size() == 0) {
            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();

    }

    private void hideEmptyView() {
        //swipeLayout.setVisibility(View.VISIBLE);
        rlEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }

    private void showContentEmptyView() {
        //swipeLayout.setVisibility(View.INVISIBLE);
        rlEmptyContentDisplay.setVisibility(View.VISIBLE);
    }

    @Override
    public void onResume() {
        super.onResume();
        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<BeforeArchiveListItem> newList) {
        if (newList != null) {
            if (newList.size() != 0) {
                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE++;
            } else {
                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);
            }
        }
    }

    @Override
    public void onRefresh() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadBeforeCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadBeforeCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
    }


    @Override
    public void goToEvaluate(int position) {
//        进入评估流程
        Intent intent = new Intent(this, EvaluateWorkflowActivity.class);
        intent.putExtra("VIN", dataList.get(position).getVin());
        intent.putExtra("thid", dataList.get(position).getThid());
        intent.putExtra("waitData",dataList.get(position));
        intent.putExtra(Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN);
        startActivity(intent);

    }

    @Override
    public void onReceive(final int position) {

        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("thid", dataList.get(position).getThid());

        ApiClient.postForm(HttpConstants.RECEIVE_RAPID_FROM_ARCHIVE, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                // 网络异常
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                try {

                    int result = new JSONObject(response).optInt("code");

                    if (result == 1) {
                        dataList.get(position).setState("3");
                        adapter.notifyDataSetChanged();
                    } else {
                        SToast.show("接收失败");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });
    }

}
